package cadtoolbox.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

public class ExternalInput extends AbstractInput {

	private int startingtime = 0;
	private int privatetime=0;
	private Double[] inputValues;
	public File file;
	
	public ExternalInput(Double[] inp, File file){
		this.inputValues = new Double[Constants.numberOfPoints];
		for(int i=0; i<Constants.numberOfPoints;i++){
			this.inputValues[i] = (i<inp.length?inp[i]:0.0D);
		}
		this.file = file;
	}

	@Override
	public boolean hasSingularity() {
		// TODO Auto-generated method stub
		return privatetime < inputValues.length;
	}

	@Override
	public double getNextSingularityTime() {
		// TODO Auto-generated method stub
		return startingtime;
	}

	@Override
	public void consummeSingularity() {
		// TODO Auto-generated method stub
		privatetime++;

	}

	@Override
	public double f(double t){
		double firstValue = ((t-this.startingtime)<inputValues.length && (t-this.startingtime>=0))?inputValues[(int) Math.floor(t)-this.startingtime]:0;
		double secondValue = ((t-this.startingtime)<inputValues.length-1 && (t-this.startingtime>=-1))?inputValues[((int)Math.floor(t))+1-this.startingtime]:firstValue;
		
		double rest =(Math.PI/2)*(t - Math.floor(t));
		rest = Math.sin(rest)*Math.sin(rest);
		//System.out.println(""+(firstValue*(1-rest)+secondValue*(rest)));
		return firstValue*(1-rest)+secondValue*rest;
		
		
	}

	@Override
	public String toMathematica(SequenceVertex seq) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void reset() {
		privatetime = startingtime;
		try {
			FileReader in = new FileReader(file);
			BufferedReader reader = new BufferedReader(in);
			String line = null;
			line = reader.readLine();
			String[] split;
			ArrayList<Double> values = new ArrayList<Double>();
			while ((line = reader.readLine()) != null){
				split= line.split("\t");
				for(int i=0; i<split.length;i++){
					values.add(Double.parseDouble(split[i]));
				}
			}
			Double[] inp = new Double[values.size()];
			inp = values.toArray(inp);
			for(int i=0; i<Constants.numberOfPoints;i++){
				this.inputValues[i] = (i<inp.length?inp[i]:0.0D);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String toString(){
		return "External input from file "+file.getName();
	}

	@Override
	public void setTime(double valueOf) {
		this.privatetime = (int) valueOf;
		this.startingtime = (int) valueOf;
		
	}

}
